package sentinel.demo02.datasource;

import com.alibaba.csp.sentinel.datasource.Converter;
import com.alibaba.csp.sentinel.datasource.FileRefreshableDataSource;
import com.alibaba.csp.sentinel.init.InitFunc;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.alibaba.fastjson.JSON;

import java.net.URL;


public class MyFileDatasource implements InitFunc {
    @Override
    public void init() throws Exception {
        //定义加载规则的代码
        System.out.println("数据源被加载");
        //读取flowRules.json文件 转化成List<FlowRule> 交给sentinel使用
        URL resource = this.getClass().getClassLoader().getResource("flowRules.json");
        String filePath= resource.getPath();
        System.out.println("拿到文件路径:"+filePath);
        FileRefreshableDataSource flowRuledataSource=
                new FileRefreshableDataSource(filePath, new Converter() {
                    @Override
                    public Object convert(Object fileContent) {
                        //入参 就是文件里文本 json字符串
                        //返回值就是转化规则对象List<FlowRule>
                        String json=(String) fileContent;
                        return JSON.parseArray(json,FlowRule.class);
                    }
                });
        //文件路径名称 参数之一 Converter转化器
        //sentinel加载数据源中的properties
        FlowRuleManager.register2Property(flowRuledataSource.getProperty());
    }
}
